package com.netdisk.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.netdisk.Domain.User;

import com.netdisk.component.UserDealComp;
import com.netdisk.service.HDFSService;
import com.netdisk.service.IUserService;
import com.qiwenshare.common.result.RestResult;
import com.qiwenshare.common.util.DateUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author DingTian
 * @since 2023-06-11
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    IUserService userService;
    @Resource
    UserDealComp userDealComp;
    @Resource
    HDFSService hdfsService;

    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @PostMapping(value = "/register")
    @ResponseBody
    public RestResult<String> addUser(@Valid @RequestBody User user) {
        System.out.println(user.toString());

        if (userDealComp.isUserNameExit(user)) {
            return RestResult.fail().message("用户名已存在！");
        }
        if (!userDealComp.isPhoneFormatRight(user.getTelephone())){
            return RestResult.fail().message("手机号格式不正确！");
        }
        if (userDealComp.isPhoneExit(user)) {
            return RestResult.fail().message("手机号已存在！");
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        user.setCreateTime(LocalDateTime.now().format(formatter));
        boolean result = userService.save(user);
        if (result) {
            hdfsService.makeFolder("/" + user.getTelephone());
            return RestResult.success();
        } else {
            return RestResult.fail().message("注册用户失败，请检查输入信息！");
        }
    }


    @GetMapping("/login")
    @ResponseBody
    public RestResult<User> userLogin(
            @Parameter(description = "登录手机号") String telephone,
            @Parameter(description = "登录密码") String password,HttpSession session) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.setEntity(new User(telephone, DigestUtils.md5Hex(password)));
        User result = userService.getOne(lambdaQueryWrapper);
        if (result == null) {
            return RestResult.fail().message("手机号或密码错误！");
        }else{
            session.setMaxInactiveInterval(60*60);
            session.setAttribute("user",result);
            return RestResult.success().data(result);
        }
    }

    @PutMapping
    public RestResult updateUser(@RequestBody User user) {
        user.setPassword(DigestUtils.md5Hex("123456"));
        System.out.println(user);
        if(userService.updateById(user)){
            return RestResult.success();
        }else {
            return RestResult.fail().message("更新失败");
        }
    }

    @DeleteMapping("/{telephone}")
    public RestResult deleteById(@PathVariable String telephone) {
        if(userService.remove(new QueryWrapper<>(new User(telephone)))){
            System.out.println("/" + telephone);
            hdfsService.deleteFile("/" + telephone);
            return RestResult.success();
        }else {
            return RestResult.fail().message("删除失败");
        }
    }

    @PostMapping("/page")
    public RestResult<IPage<User>>  selectByPageAndCondition(@RequestBody User user, @RequestParam long currentPage, @RequestParam long pageSize) throws IOException {
        IPage<User> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        String username = user.getUsername();
        String telephone = user.getTelephone();
        String password = user.getPassword();
        lqw.like(User::getUsername, username);
        lqw.like(User::getTelephone, telephone);
        lqw.like(User::getPassword,password);
        IPage<User> page1 = userService.page(page, lqw);
        List<User> records = page1.getRecords();
        for (User user1 : records) {
            user1.setStorage_size(hdfsService.getSize("/" + user1.getTelephone()));
        }
        return  RestResult.success().dataList(records,records.size());
    }

    @Operation(summary = "检查用户登录信息", tags = {"user"})
    @GetMapping("/checkuserlogininfo")
    public RestResult<User> checkUserLoginInfo(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        if(user != null){
            return RestResult.success().data(user);
        } else {
            return RestResult.fail().message("用户暂未登录");
        }

    }

    @Operation( description = "退出登录，删除session")
    @PostMapping("/logout")
    public RestResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        session.invalidate();
        return RestResult.success();
    }

}

